package akbderby.page;

import java.util.List;
import java.util.logging.Logger;

import org.slim3.controller.Navigation;
import org.slim3.controller.upload.FileItem;
import org.slim3.datastore.Datastore;
import org.slim3.util.BeanUtil;

import scenic3.annotation.ActionPath;
import scenic3.annotation.Default;
import scenic3.annotation.Page;
import scenic3.annotation.Var;
import akbderby.model.Blobstore;
import akbderby.model.UploadedData;
import akbderby.service.UploadService;

import com.google.appengine.api.datastore.Key;
import com.google.appengine.api.datastore.KeyFactory;

@Page("/edit")
public class EditPage extends BasePage {

    protected static final Logger logger = Logger.getLogger(EditPage.class
        .getName());

    private UploadService service = new UploadService();

    @ActionPath("upload")
    public Navigation upload() throws Exception {
        if (!getUser().isAdmin())
            return redirect("/");

        // BlobstoreService bs = BlobstoreServiceFactory.getBlobstoreService();
        // Map<String, BlobKey> blobs = bs.getUploadedBlobs(request);

        FileItem formFile = requestScope("formFile");

        UploadedData data = service.upload(formFile);

        if (data != null) {
            Blobstore blobstore = new Blobstore();
            // blobstore.setKey(Datastore.allocateId(BlobstoreMeta.get()));
            blobstore.setImageKey(data.getKey());
            blobstore.setImageVersion(data.getVersion());
            BeanUtil.copy(request, blobstore);
            Datastore.put(blobstore);
        }
        // ServletFileUpload upload = new ServletFileUpload();
        // // response.setContentType("image/jpeg");
        // FileItemIterator iterator = upload.getItemIterator(request);
        // while (iterator.hasNext()) {
        // FileItemStream item = iterator.next();
        // InputStream stream = item.openStream();
        //
        // if (item.isFormField()) {
        // logger.warning("Got a form field: " + item.getFieldName());
        // } else {
        // logger.warning("Got an uploaded file: "
        // + item.getFieldName()
        // + ", name = "
        // + item.getName());
        //
        // // You now have the filename (item.getName() and the
        // // contents (which you can read from stream). Here we just
        // // print them back out to the servlet output stream, but you
        // // will probably want to do something more interesting (for
        // // example, wrap them in a Blob and commit them to the
        // // datastore).
        // int len;
        // byte[] buffer = new byte[8192];
        // while ((len = stream.read(buffer, 0, buffer.length)) != -1) {
        // response.getOutputStream().write(buffer, 0, len);
        // }
        // }
        // // BlobKey blobKey = blobs.get("formFile");
        // // if (blobKey != null) {
        // // Key key =
        // // Datastore.createKey(Blobstore.class, blobKey.getKeyString());
        // // Blobstore blobstore = new Blobstore();
        // // blobstore.setKey(key);
        // // Datastore.put(blobstore);
        // // }
        // }
        // return redirect(basePath);
        return redirect(basePath);
    }

    @ActionPath("show/{id}")
    public Navigation show(@Var("id") String id) throws Exception {
        if (!getUser().isAdmin())
            return redirect("/");

        // Key key = Datastore.createKey(Blobstore.class, id);
        Key key = KeyFactory.stringToKey(id);
        Blobstore blobstore = Datastore.get(Blobstore.class, key);
        UploadedData data =
            service.getData(
                blobstore.getImageKey(),
                blobstore.getImageVersion());
        byte[] bytes = service.getBytes(data);
        show(data.getFileName(), bytes);
        // BlobKey blobKey = new BlobKey(id);
        // BlobstoreService bs = BlobstoreServiceFactory.getBlobstoreService();
        // bs.serve(blobKey, response);
        return null;
    }

    @ActionPath("edit/{id}")
    public Navigation edit(@Var("id") String id) throws Exception {
        if (!getUser().isAdmin())
            return redirect("/");

        Key key = KeyFactory.stringToKey(id);
        Blobstore blobstore = Datastore.get(Blobstore.class, key);
        BeanUtil.copy(blobstore, request);
        return forward("/edit/edit.jsp");
    }

    @ActionPath("update/{id}")
    public Navigation update(@Var("id") String id) throws Exception {
        if (!getUser().isAdmin())
            return redirect("/");
        Key key = KeyFactory.stringToKey(id);
        Blobstore blobstore = Datastore.get(Blobstore.class, key);
        BeanUtil.copy(request, blobstore);
        Datastore.put(blobstore);
        return redirect("/edit/edit/" + id);
    }

    @ActionPath("delete/{id}")
    public Navigation delete(@Var("id") String id) throws Exception {
        if (!getUser().isAdmin())
            return redirect("/");

        Key key = KeyFactory.stringToKey(id);
        Blobstore blobstore = Datastore.get(Blobstore.class, key);
        service.delete(blobstore.getImageKey());
        Datastore.delete(key);
        return redirect("/edit/");
    }

    @Default
    public Navigation index() {
        if (!getUser().isAdmin())
            return redirect("/");

        requestScope("group", "SKE48");
        List<Blobstore> dataList = Datastore.query(Blobstore.class).asList();
        requestScope("dataList", dataList);
        // BlobstoreService blobstoreService
        // = BlobstoreServiceFactory.getBlobstoreService();
        // String uploadUrl = blobstoreService.createUploadUrl("/edit/upload");
        // requestScope("uploadUrl", uploadUrl);
        return forward("/edit/editList.jsp");
    }
}
